﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace BIStudio.Framework.Log.Common.Internal
{
    /// <summary>
    /// 日志工厂
    /// </summary>
    internal class LogFactory
    {
        /// <summary>
        /// 缓存logprovider 
        /// key为子类的描述特性
        /// </summary>
        private static Dictionary<string, Type> _logs;

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static ILog CreateLog(string providerName)
        {
            if (_logs == null)
            {
                _logs =
                    Assembly.GetExecutingAssembly()
                        .GetTypes()
                        .Where(item => item.GetInterfaces().Contains(typeof (ILog)))
                        .ToDictionary(item =>
                        {
                            var desc = item.GetCustomAttribute<DescriptionAttribute>();
                            return desc != null ? desc.Description.ToLower() : string.Empty;
                        }, item => item);
            }
            if (!_logs.ContainsKey(providerName.ToLower()))
                _logs.Add(providerName, typeof (LocalLogProvider));
            return (ILog) Activator.CreateInstance(_logs[providerName.ToLower()]);
        }
    }
}